package com.kingyea.mobilepolice.system.job;

import com.alibaba.fastjson.JSON;
import com.kingyea.app.market.client.MarketServiceClient;
import com.kingyea.app.market.market.bean.Market;
import com.kingyea.app.market.utils.GlobalVar;
import com.kingyea.app.market.utils.StateCode;
import com.kingyea.mobilepolice.system.Result;
import com.kingyea.mobilepolice.system.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

/**
 * GlobalJob
 *
 * @author Mr.Lin
 * @version v1.0.0
 * @description
 * @date Created in 2018/01/08 16:30
 */
@Component
public class GlobalJob {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalJob.class);

    /**
     * 是否已经初始化
     */
    private static boolean isInit = false;
    private static int tryNum = 0;
    @Autowired
    private MarketServiceClient marketServiceClient;

    /**
     * 提供定时任务查询是否已经初始化项目
     */
    public static boolean isIsInit() {
        return isInit;
    }

    /**
     * 项目初始化
     **/
    @Scheduled(initialDelay = 10, fixedRate = 99999999)
    public void init() throws Exception {
        if (!isInit) {
            // TODO: 2018/3/26 获取自身市场身份
            initMyMarket();


            isInit = true;// 第一次初始化完成，之后不在执行这个方法
            LOGGER.info("项目初始化完成... ");
        }
    }

    /**
     * 初始化自身市场身份
     *
     * @param
     * @return void
     * @author Mr.Lin
     * @date 2018/3/27 10:21
     */
    private void initMyMarket() throws Exception {
        try {
            LOGGER.info("正在初始化自身市场身份...");
            Result<List<Market>> myMarketListResult = marketServiceClient.queryList(new HashMap<String, Object>() {{
                put("localMarket", 1);
            }});
            if (!myMarketListResult.getCode().equals(StateCode.OPERATION_SUCCESS)) {
                LOGGER.error("获取数据异常：{}", JSON.toJSONString(myMarketListResult));
                throw new BusinessException(StateCode.SERVER_DATA_ERROR);
            }
            List<Market> myMarketList = myMarketListResult.getData();
            if (myMarketList == null || (myMarketList.size() != 1)) {
                if (myMarketList == null || (myMarketList.size() <= 0)) {
                    LOGGER.error("数据异常，请重新初始化数据!!!!");
                    if (GlobalVar.getIsDev()) {
                        LOGGER.error(" 警告：开发模式，跳过重试！！！ ");
                        return;
                    }
                    throw new BusinessException(StateCode.SERVER_DATA_ERROR);

                }
            }
            Market myMarket = myMarketList.get(0);
            GlobalVar.marketCode = myMarket.getMarketCode();
            GlobalVar.marketClassify = myMarket.getMarketClassify();
            GlobalVar.adminMarket = myMarket.getAdminMarket();
        } catch (Exception e) {
            if (tryNum < 30) {
                tryNum++;
                e.printStackTrace();
                LOGGER.error("初始化自身市场身份失败，5s后重试... ");
                Thread.sleep(5000);
                initMyMarket();
            }
        }

    }


}
